<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/20/020
 * Time: 9:14
 */

namespace app\Lib\Model\Login;


class WeiXiGetOpenId
{
    private $appid ='wx6252ec6e2f981417';
    private $scope ='snsapi_base';
    private $code = '';
    private $secret = 'a15b0caf6f3b0a506534ccb06fe65c20';
    public function setCode($code){
        $this->code = $code;
    }
    // 通过code获得openid
    public function getCode() {
            // 获取当前打开页面的完整访问路径
            $baseUrl = 'http://' . $_SERVER ['HTTP_HOST'] .'/index/WeiXinOpenIdLogin/weiXinLogin';
            $baseUrl = urlencode ( $baseUrl );
            //配置获取code 路径的相关参数
            $paramsArr                   = array();
            $paramsArr ["appid"]         = $this->appid;
            $paramsArr ["redirect_uri"]  = "$baseUrl";
            $paramsArr ["response_type"] = "code";
            //scope 应用授权作用域
            $paramsArr ["scope"]         = $this->scope;
            //state 非必须参数，重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
            //结尾 #wechat_redirect 必须有，且该字符串前面不能带 & 所以连接到最后一个参数值后面，无论直接打开还是做页面302重定向时候，必须带此参数
            $paramsArr ["state"]         = "STATE" . "#wechat_redirect";
            //将数组变成参数url
            $paramsUrl = $this->arrToParams ( $paramsArr );
            //构造获取code的访问路径，访问后，微信服务器会再跳回$baseUrl指定的页面（这里当前页），并返回 code 码
            $codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $paramsUrl;
            Header ( "Location: $codeUrl" );
            exit ();
    }

    public function getOpenId(){
        $code = $this->code;
        //配置获取 openid 路径的相关参数
        $paramsArr                = array();
        $paramsArr ["appid"]      = $this->appid;
        $paramsArr ["secret"]     = $this->secret;
        $paramsArr ["code"]       = $code;
        $paramsArr ["grant_type"] = "authorization_code";
        $paramsUrl = $this->arrToParams ( $paramsArr );
        $openidUrl =  "https://api.weixin.qq.com/sns/oauth2/access_token?" . $paramsUrl;


        $data = $this->httpCurl ( $openidUrl );
        $openid = $data['openid'];
        if($this->scope == 'snsapi_userinfo'){
            //如果是显示授权，即需要用户点击授权，则还会返回 access_token 通过 access_token 及 openid 通过 echo file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN");即可获取打印用户信息，或者用这里的curl方法httpCurl(https://api.weixin.qq.com/sns/userinfo?access_token=...)获取亦可
            $access_token = $data['access_token'];
        }
        return $openid;
    }


    /**
     *
     * 拼接签名字符串
     *
     * @param array $paramsArr
     *
     * @return string
     */
    private function arrToParams($paramsArr) {
        $buff = "";
        foreach ( $paramsArr as $k => $v ) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim ( $buff, "&" );
        return $buff;
    }


    /**
     *
     * 通过code从工作平台获取openid机器access_token
     *
     * @param string $code
     *            微信跳转回来带上的code
     *
     * @return array
     */
    public function httpCurl($url) {
        $wxPayConfig ['CURL_PROXY_HOST'] = "0.0.0.0"; // "10.152.18.220";
        $wxPayConfig ['CURL_PROXY_PORT'] = 0;
        // 初始化curl
        $ch = curl_init ();
        // 设置30秒超时
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_HEADER, FALSE );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
        if ($wxPayConfig ['CURL_PROXY_HOST'] != "0.0.0.0" && $wxPayConfig['CURL_PROXY_PORT'] != 0) {
            curl_setopt ( $ch, CURLOPT_PROXY, $wxPayConfig ['CURL_PROXY_HOST'] );
            curl_setopt ( $ch, CURLOPT_PROXYPORT, $wxPayConfig ['CURL_PROXY_PORT'] );
        }
        // 运行curl，结果以jason形式返回
        $res = curl_exec ( $ch );
        curl_close ( $ch );
        // 取出openid
        $data = json_decode ( $res, true );
        return $data;
    }
}